Skip to content

Model std::move and std::forward in C++ lowering (#293) - #300

Open
IvanTrofimov052 wants to merge 37 commits into
masterfrom
fix/std-move-forward-293
Open

IvanTrofimov052 wants to merge 37 commits into
masterfrom
fix/std-move-forward-293

Conversation

@IvanTrofimov052

Copy link
Copy Markdown
Collaborator

No description provided.

Comment on lines +1094 to +1106
let reference = func.parameter_references.get(slot).copied().flatten();
let value = func.reference_params.get(slot) == Some(&false)
&& params
.get(index)
.and_then(|ty| program.types.all().get(ty.0 as usize))
.is_some_and(|ty| {
ty.desc.is_pointer_like() || matches!(*ty.desc, TypeDesc::Array { .. })
});
(reference, value)
});
trace_ir::append_signature_references(&mut sig, bindings);
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possible Off-by-one

The by-value value flag is read from func.reference_params.get(slot) using the same slot that is built for explicit_params/parameter_references. explicit_params and parameter_references cover explicit parameters only, whereas the reference_params documentation says it also records the member's implicit this (as entry 0). For a member function the slot is therefore one position short in reference_params: the flag is taken from the preceding parameter (for the first explicit parameter it happens to match this, which is by value). Concretely, exporting a member such as void C::f(T* &a, T* b) records the second parameter as - instead of value, so an overload f(T* &, T* &) and f(T* &, T*) become signature-compatible in trace-merge and can be merged/mislinked across databases. Suggested correction: index reference_params with the this offset (e.g. slot + usize::from(has_this_param)) so it aligns with parameter_references, and add a merge fixture with a member function mixing reference and by-value pointer parameters. Uncertainty: this depends on explicit_params excluding this (the function is not shown in the diff); if reference_params is in practice explicit-only, the current indexing is fine.

@devnullexile-deepseek-review

devnullexile-deepseek-review Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 80f28cd)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis ✅

293 - PR Code Verified

Compliant requirements:

  • AC1 spellings, macros and explicit template arguments
  • AC2 unqualified, using-declaration and namespace-alias spellings for flow and receiver dispatch
  • Explicit template argument used for receiver typing
  • Value-category-aware ref-qualified overload, constructor and parameter ranking
  • Copy-initialization and assignment operator edges
  • Functor dispatch through std::move, parentheses and static_cast
  • Moved-from behaviour documented as intentional over-approximation
  • Exported move/forward edges kept and documented
  • Docs and eval expectation updates
  • Moved-from / object-aliasing over-approximations are documented in docs/FAQ.md.

Requires further human verification:

  • The recaptured HDF / HiView / Camera / Ability Runtime centers in scripts/eval_expected.json cannot be validated by code review; a pinned corpus run is needed.
  • All code-level acceptance criteria: the substantive lowering changes are in crates/trace-parse/src/lower.rs, which is outside the reviewed diff.
  • AC1 spelling/regression guard and AC2 unqualified/alias spellings for value flow and receiver typing.
  • Explicit template-argument receiver typing, ref-qualified overload narrowing, copy-init/assignment modelling, functor operator() dispatch.
  • Decision and implementation status for the exported move/forward call edge.
  • Documentation updates to docs/CXX.md, docs/IR.md, and docs/MODELS.md (not shown in the reviewed diff).
  • New/updated fixtures and eval expectation changes.
⏱️ Estimated effort to review: 5 🔵🔵🔵🔵🔵
✅ Merge recommendation: Changes required
🧪 PR contains tests
🔒 No security concerns identified

ℹ️ Chunked review: the diff exceeded the model token budget, so it was reviewed in 2 chunks and the per-chunk results were merged.

✅ Resolved findings

crates/trace-db/src/export.rs:1094-1106

Possible Off-by-one

The by-value value flag is read from func.reference_params.get(slot) using the same slot that is built for explicit_params/parameter_references. explicit_params and parameter_references cover explicit parameters only, whereas the reference_params documentation says it also records the member's implicit this (as entry 0). For a member function the slot is therefore one position short in reference_params: the flag is taken from the preceding parameter (for the first explicit parameter it happens to match this, which is by value). Concretely, exporting a member such as void C::f(T* &a, T* b) records the second parameter as - instead of value, so an overload f(T* &, T* &) and f(T* &, T*) become signature-compatible in trace-merge and can be merged/mislinked across databases. Suggested correction: index reference_params with the this offset (e.g. slot + usize::from(has_this_param)) so it aligns with parameter_references, and add a merge fixture with a member function mixing reference and by-value pointer parameters. Uncertainty: this depends on explicit_params excluding this (the function is not shown in the diff); if reference_params is in practice explicit-only, the current indexing is fine.

@devnullexile-deepseek-review

devnullexile-deepseek-review Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

DeepSeek review: Not approved (80f28cd)

To get the bot's approval:

This is review 5 of this pull request. After 3 reviews the model's findings no longer block approval (max-blocking-reviews); security concerns, files not fully reviewed, open threads of the bot and paths a person approves still do.

Not blocking:

  • crates/trace-merge/src/lib.rs:414 Legacy declaration merge defeated by duplicate entries: `shared_declaration` accepts an unannotated legacy declaration only when its filtered input list has exactly one entry (`compatible.next().is_none()`). However `header_decl_map` is filled with `push(new_fn_id)` for every input copy, including copies that were merged into the same existing row, so t… (raised after the last review that can block)

For a person to review, too large for GitHub to send to the model, so it did not see them: crates/trace-parse/src/lower.rs.

This comment is updated on every review. The review comment and its threads have the details.

@ArcsinX ArcsinX left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed PR #300 (401cec5f). Found 5 issues in overload/redeclaration matching, copy-initialization constructor filtering, alias reference qualification, and ADL pointer-reference validation (see inline comments).

Comment thread crates/trace-ir/src/symbol.rs Resolved
Comment thread crates/trace-parse/src/lower.rs Resolved
Comment thread crates/trace-parse/src/lower.rs Resolved
Comment thread crates/trace-parse/src/lower.rs Resolved
Comment thread crates/trace-parse/src/lower.rs Resolved

@DrSergei DrSergei left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. ADL now binds the global namespace (adl_namespaces, crates/trace-parse/src/lower.rs) for class-typed args with no qualifier, plus template args, bases, and enum namespaces. C++-correct, but an unqualified call inside a namespace can now bind a same-named global function — so a name-keyed libc model (e.g. epoll_wait) could fire on a coincidental match with a different signature. The tests/fixtures/epoll/main.cpp change (epoll_wait → other::epoll_wait) looks like a workaround for this. Behavior change; verify model synthesis can't attach to unrelated unqualified calls.
  2. Receiver typing widened: receiver_desc switched from cast_receiver_desc (required owning pointer) to cast_class_desc (any class referent); the former was removed (lower.rs:23826–23835). Broader than the feature — affects all class-typed casts (static_cast(x).m(), (Foo*)p). Plausibly intentional but undocumented; check it doesn't add/retarget unrelated edges.
  3. signature_references_compatible ignores arity (crates/trace-ir/src/types.rs) — zip silently treats differing-length reference lists as compatible. Safe today (same-storage callers only); an explicit length guard or pinned-precondition comment would document the invariant. Low severity.
  4. Per-unit maps unbounded: local_reference_categories and adl_template_types are never truncated on scope exit (unlike using_nss/local_namespace_aliases). Keyed by unique VarId, so growth is bounded per TU — not a correctness issue. Note only.

@devnullexile devnullexile left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found 3 issues in auto && forwarding-reference category recording, absorb_redeclaration merging of variable-length parameter_references, and respelled_declarations alignment with the new reference-form overload separation.

Some(decl),
declaration.cached_field("type"),
) {
ctx.local_reference_categories.insert(var_id, rvalue);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] declared_reference_kind returns Some(true) for a local forwarding reference auto &&r = s; (the declarator spells && and type_reference_kind is None for auto), so local_reference_categories records r as an rvalue reference even when s is an lvalue and auto && collapses to S&. Subsequent std::forward<decltype(r)>(r).m(), sink(std::forward<decltype(r)>(r)), or S b = std::forward<decltype(r)>(r); then select && overloads and drop the & / copy overloads, violating AGENTS.md ("Soundness: May-analysis — over-approximate when uncertain"). For unqualified placeholder auto &&, derive the category from the initializer or omit it when unknown so decltype_reference_kind stays conservative.

_ => {}
}
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Because ParamListShape::record only extends reference_forms up to the last known reference parameter, an earlier declaration with an opaque alias in a later slot (e.g. void f(T &a, RefB b);) can have a shorter parameter_references vector than a redeclaration/definition that resolves it (void f(T &a, const U &b) {}). Here zip stops at existing.parameter_references.len() and silently drops trailing entries from func.parameter_references.

Suggested change
}
if func.parameter_references.len() > existing.parameter_references.len() {
existing
.parameter_references
.extend_from_slice(&func.parameter_references[existing.parameter_references.len()..]);
}
}

// declarations too.
if existing.is_const_member != func.is_const_member
|| existing.ref_qualifier != func.ref_qualifier
|| !Self::reference_forms_alike(existing, func)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Now that SymbolTable separates C++ overloads by reference_forms_alike, respelled_declarations in crates/trace-parse/src/merge.rs is out of sync because its candidate filter does not check SymbolTable::references_alike(f, declaration). In a TU with an undefined internal declaration static void f(const T &); alongside static void f(T &&) {}, respelled_declarations matches them by identical IR storage type (T*) and merges f(const T &) into f(T &&); conversely, two respelled static overloads (const ns::T & and ns::T &&) block each other from linking to their definitions.

@ArcsinX ArcsinX left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed PR #300 (d90846a9). All 5 previous findings from 401cec5f are addressed (and resolved). Found 6 remaining issues in forwarding-reference decltype resolution, allocator specialization signature matching / declaration merging, lower_class_assignment defaulted-move fallback, and lower_copy_initialization compound std::forward glvalues (see inline comments).

Comment thread crates/trace-parse/src/lower.rs Resolved
Comment thread crates/trace-parse/src/lower.rs Resolved
Comment thread crates/trace-parse/src/lower.rs Resolved
Comment thread crates/trace-parse/src/lower.rs Resolved
Comment thread crates/trace-parse/src/lower.rs Resolved
Comment thread crates/trace-ir/src/symbol.rs Resolved

@DrSergei DrSergei left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Unknown/omitted template args treated as "no match" — real bug
    crates/trace-ir/src/symbol.rs:369-406
    specialization_matches_template_args only returns Some(true) when limit is Some, lengths match exactly, and every arg pair is Some and equal. Everything else falls through to Some(false):
  • limit == None (no unique primary / no allocator metadata, or unbounded pack).
  • Any None written or specialization argument (1 + 1, unresolved type, defaulted/omitted trailing arg).
  • A partial template-id where written.len() != args.len().
    The caller at lower.rs:27090 treats Some(false) as "remove candidate" and None as "keep as uncertain", so this definitively drops a specialization that should remain a possible match. This is inconsistent with docs/IR.md ("Unknown or omitted arguments retain possible matches"). Fix: return None for unknown/omitted/unknown-limit cases (and allow omitted trailing args if defaults are supported).
  1. aggregate_has_default_initializer memo key is path-dependent — lower severity
    crates/trace-parse/src/lower.rs:15045-15094
    Key is (TypeId, seen.len()), but the result also depends on seen contents (seen.contains(name)), so sibling paths reaching the same type at the same depth share a cache entry computed under a different cycle context. Requires cyclic/recovered layouts to occur, hence limited severity. Either include seen in the key or avoid memoizing results produced with a cycle truncation; the current comment ("keep the remaining depth budget in the key") doesn't cover the cycle-set dependency.

@devnullexile devnullexile left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed 401cec5f..d90846a9. All three findings from my previous review are fixed in the code.

  • Local auto&& now collapses correctly for the named lvalue in the original repro. Earlier comment
  • Redeclarations now preserve trailing reference metadata. Earlier comment
  • Respelled internal declarations now check reference compatibility. Earlier comment

&& !declaration_has_const(source, declaration)
{
init_expr
.and_then(|init| receiver_value_category(program, ctx, source, init, false))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve the value category of xvalue array elements

With S (&items)[2], auto&& r = std::move(items)[0]; deduces S&&. receiver_value_category treats array subscripts as lvalues, so this now records r as S&. In a fixture with S::f() & and S::f() &&, std::forward<decltype(r)>(r).f() produced only the && edge at 401cec5f and now produces only the & edge. An array subscript should inherit the array operand's value category. A pointer subscript still produces an lvalue.

Comment thread crates/trace-parse/src/lower.rs Outdated
/// receiver substitution drops qualifiers that can distinguish owners here.
fn explicit_class_specialization_key(head: &str, spelling: &str) -> Option<String> {
let arguments = &spelling[spelling.find('<')?..];
Some(format!("{head}{}", normalize_spacing(arguments)))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Canonicalize explicitly specialized owner types before counting template prefixes

template<> struct Alloc<int const> and an out-of-class specialization written as template<> Tag* Alloc<const int>::malloc(int) name the same owner. The raw argument keys differ, so the owner consumes the sole template<> prefix and the definition loses its allocator-specialization metadata. With template<class... P> static Tag* malloc(P..., int) as the primary, Alloc<const int>::malloc<>(7) used to emit only the specialization edge and now emits only the primary edge. Compare the owner arguments by type identity so equivalent cv spellings and aliases preserve the member specialization.

Comment thread crates/trace-ir/src/symbol.rs Outdated
|id| {
let candidate = self.function(id);
selected.variadic == candidate.variadic
&& selected.same_allocator_specialization(candidate)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep ordinary members out of selected template initializer targets

Declare both static Tag* malloc(Tag*) and template<class T> static Tag* malloc(Tag*) in Arena, then define both in a second TU. For Tag* observed = Arena::malloc<int>(&wrong);, the selected template returns &correct and the ordinary overload returns its argument. This filter admits both definitions because neither is an explicit specialization and the parameter types match. The new wiring therefore adds wrong to observed's points-to set alongside correct. Match member-template identity before wiring the initializer's arguments and return.

Preserve unknown forwarding categories, xvalue array element bindings, and copy fallbacks after deleted defaulted move assignment. Avoid sharing aggregate-default misses that depended on a cycle cutoff.

Keep allocator template identity through redeclaration, ranking, and selected initializer resolution. Canonicalize class owner arguments with their lexical type aliases and qualifiers.

Review dispositions: reference_params is explicit-only and export emits [refs=&:m,value] for the mixed member signature. Local auto&& collapse, reference metadata growth, respelled reference compatibility, and alias-only owner matching were already covered before this change. The tri-state template match already retained unresolved arguments via None.

@DrSergei DrSergei left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • [P2] Keep free allocator templates distinct from ordinary overloads — D:\projects\pathologist\crates\trace-ir\src\symbol.rs:2324-2326
    When a non-template malloc(int) definition and a template malloc(int) declaration are both visible, symbol registration merges them because it does not compare is_free_function_template. The merged row inherits the template flag, so malloc<>(0) incorrectly reaches the ordinary body in both a function and a file-scope initializer. Include free-template status in the shared C++ redeclaration check (AGENTS.md:153 (AGENTS.md#L153)).
  • [P2] Export allocator specialization identity for database relinking — D:\projects\pathologist\crates\trace-db\src\export.rs:1097-1099
    When a consumer database calls malloc<1>(0) and a provider defines both malloc<1>(int) and malloc<2>(int), both specializations export as malloc(int). In a local merge, the call became ambiguous and gained edges to both specializations, the primary, and the ordinary overload. Carry the template identity already used by the in-memory resolver into the exported signature and relinking comparison (AGENTS.md:153 (AGENTS.md#L153)).
  • [P2] Bind allocator specialization defaults from the primary template — D:\projects\pathologist\crates\trace-parse\src\lower.rs:27305-27307
    An explicit function-template specialization uses default arguments from its primary even though the specialization cannot declare those defaults itself. After malloc(0) selects a specialization, the primary is discarded and neither body calls nor file-scope initializers bind its omitted arguments. With template Fn malloc(T, Fn cb = hit) and a specialization that returns cb, the subsequent indirect call loses its only target. Keep the specialization as the callee but use the primary as the default-argument source.
  • [P2] Use selected allocator specializations for result typing — D:\projects\pathologist\crates\trace-parse\src\lower.rs:10066-10073
    Call-edge resolution filters allocator specializations by their written template arguments, but static result inference still ranks the unfiltered overload set. With malloc(int) returning A* and malloc(int) returning B*, malloc(0)->Touch() gets the correct allocator edge but no B::Touch edge; the same happens through an auto* local. Reuse the specialization filter for result inference so the call and its result agree (AGENTS.md:153 (AGENTS.md#L153)).
  • [P2] Keep allocator target selection independent of model overrides — D:\projects\pathologist\crates\trace-analysis\src\summaries.rs:796-804
    Registering a custom malloc model removes it from c_api_models, which also disables occurrence-based return resolution for every malloc overload, including Arena::malloc. With Arena::malloc(int) and Arena::malloc(void*) returning different callbacks, adding an unrelated global malloc model made the indirect call reach both callbacks even though the direct edge still selected the int overload. Index selected targets independently of which summaries are enabled (AGENTS.md:153 (AGENTS.md#L153)).
  • [P2] Use the declared type for unparenthesized member decltype — D:\projects\pathologist\crates\trace-parse\src\lower.rs:26773-26775
    For std::forward<decltype(h.member)>(h.member), C++ uses the member's declared type: a member declared M yields an rvalue, while one declared M& yields an lvalue. Returning unknown for every unparenthesized field expression retains both ref-qualified overloads. When those overloads return different classes, the analyzer also drops the next call in the chain. Use the member declaration's reference category and qualification for this form of decltype.
  • [P2] Preserve auto&& binding for built-in address-of initializers — D:\projects\pathologist\crates\trace-parse\src\lower.rs:15263-15268
    For auto&& r = &n, the initializer is a pointer prvalue and decltype(r) is int*&&. The category probe does not recognize built-in address-of, so std::forward<decltype(r)>(r) retains both int*& and int*&& overloads. If their return types differ, this also loses a chained member call. Classify known built-in address-of expressions as prvalues when recording the collapsed binding.

@devnullexile devnullexile left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed d90846a9..82466755 (no replies to earlier comments).

Status of my earlier review comments:

  • Resolved for true array references (S (&items)[2]): auto&& r = std::move(items)[0] now collapses to an rvalue reference (earlier comment), though decayed array parameters regressed (see inline).
  • Resolved for single-template owners and aliases (Alloc<int const>, Alloc<ConstKey>, Alloc<const int>) (earlier comment), though nested explicit specializations regressed (see inline).
  • Resolved: initializer_declaration_candidates now checks same_template_signature, keeping ordinary members out of selected template initializer targets (earlier comment).

Found 8 new issues in the changes since d90846a9 (see inline comments).

Comment thread crates/trace-parse/src/lower.rs Outdated
let prefix = &source[start..arguments.start_byte()];
if key.is_empty() {
let head = normalize_qualified(prefix);
if let Some(declared) = declared_head.filter(|_| !head.contains("::")) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Only apply declared_head when the owner is a single unqualified template

For a nested explicit class specialization such as template<> struct Outer<int>::Inner<int>, lower_struct_specifier passes declared_head = Some("Outer::Inner"). On the first loop iteration (Outer<int>), prefix is "Outer", so !head.contains("::") is true and key substitutes "Outer::Inner" in place of "Outer", recording "Outer::Inner<int>::Inner<int>" instead of "Outer<int>::Inner<int>". allocator_template_metadata then looks up "Outer<int>::Inner<int>", misses, counts Inner<int> as an unspecialized owner template, and drops the member specialization metadata.

With Outer<int>::Inner<int>::malloc<>(7), d90846a9 resolved the return to the explicit specialization (spec3), whereas 82466755 falls back to the primary (primary3) (and loses the return entirely inside a namespace).

Suggested change
if let Some(declared) = declared_head.filter(|_| !head.contains("::")) {
if let Some(declared) =
declared_head.filter(|_| qualified.id() == last.id() && !head.contains("::"))
{

Comment on lines +11222 to +11223
TypeDesc::Array { .. } => {
receiver_value_category(program, ctx, source, operand, false)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Treat decayed array parameters as pointer subscripts

In C++ ([dcl.fct]/5), a non-reference array parameter such as void f(S items[2]) or void f(S items[2][3]) adjusts to a pointer (S* / S (*)[3]), so std::move(items)[0] is a pointer subscript producing an lvalue (S&), not an xvalue. Because parameter_type and var_receiver_desc keep TypeDesc::Array for non-reference StorageClass::Param variables, this branch now inherits std::move(items)'s rvalue category.

In a fixture with S::call() &/&& and S(const S&)/S(S&&), both auto&& r = std::move(items)[0]; std::forward<decltype(r)>(r).call(); and S copy = std::move(items)[0]; emitted only & / S(const S&) at d90846a9 and now emit only && / S(S&&), dropping the real target. Only non-decayed arrays (including array references such as S (&items)[2]) should inherit the operand's value category.

Comment on lines +15479 to +15481
"field_expression" | "subscript_expression" => {
receiver_value_category(program, ctx, source, value, false).map(Some)
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve unknown glvalue categories through subscript and member access

initializer_glvalue now returns Option<Option<bool>> so unknown-category glvalues (Some(None)) still emit copy/move constructor candidates in lower_copy_initialization, and subscript_expression was added here. However, .map(Some) turns receiver_value_category's None back into None (not a glvalue) whenever the base is a dependent std::forward<T>(...).

For template<class T> void f(S (&items)[2]) { S copy = std::forward<T>(items)[0]; } (and c ? std::forward<T>(items)[0] : other, or S copy = std::forward<T>(h).s;), lower_copy_initialization now returns early and drops both S(const S&) and S(S&&) (the subscript forms previously emitted S(const S&) at d90846a9). Propagate initializer_glvalue through built-in array subscripts and non-reference dot member accesses so an unknown-category glvalue operand yields Some(None).

Comment thread crates/trace-parse/src/lower.rs Outdated
Comment on lines +27138 to +27152
written_arguments_complete: !defaults
&& return_type.is_none_or(|ty| {
!spelling_is_dependent(ctx, source, ty, node_text(source, &ty), Spelling::Source)
})
&& find_params(decl).is_some_and(|params| {
!params.named_children(&mut params.walk()).any(|param| {
spelling_is_dependent(
ctx,
source,
param,
node_text(source, &param),
Spelling::Source,
)
})
}),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Check the full declarator before marking allocator template arguments complete

written_arguments_complete only checks trailing_return_type, declared_return_type_node(node) (the base specifier), and find_params(decl) (which stops at the outermost function_declarator). That misses template parameters appearing in an outer declarator (template<int N> Tag (*malloc(int))[N]) or in an inner function_declarator wrapped by a function-pointer return (template<class T> Tag* (*malloc(T))(int)).

For both forms, an explicit specialization that deduces the argument (template<> Tag* (*malloc(int))(int) { return &helper; } or template<> Tag (*malloc(int))[4] { return &arr; }) is marked complete: true with arguments: [], so malloc<int>(7) / malloc<4>(7) rejects it on length mismatch (0 != 1) and drops the specialization edge and return value (helper / arr), regressing d90846a9. Check the whole declarator decl for dependent spellings before setting written_arguments_complete.

Comment thread crates/trace-parse/src/lower.rs Outdated
Comment on lines +9392 to +9395
let can_collapse = parameter_has_placeholder_type(ctx, node)
|| (dependent
&& !class_spelling_of_desc(program.types.get(type_id).desc.as_ref())
.is_some_and(|name| program.types.declares_class(name)));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep dependent member types eligible for reference collapsing

Testing declares_class on type_id classifies dependent member types as non-collapsing class rvalue references in two cases, regressing 9ef37023:

  • For a forward-declared or arrow-bearing class template (template<class T> struct Traits;), typename Traits<T>::type&& x lowers type_id as Traits<T>::type. TypeTable::declares_class splits at < and checks Traits, returning true, so can_collapse is false. std::forward<decltype(x)>(s).call() and S copy = std::forward<decltype(x)>(s); then lose all S::call and S::S edges.
  • For a member reference alias (template<class T> struct Box { using type = S&; };), typename Box<T>::type&& x resolves type_id to S (declares_class("S") == true), while declaration_reference_kind misses the dependent alias spelling and returns Some(true). can_collapse becomes false, so std::forward<decltype(x)>(s).call() and sink(std::forward<decltype(x)>(s)) emit only && and drop the only valid & target.

Only exclude a dependent T&& from collapsing when the parameter type node itself directly names a declared class template specialization (not a dependent_type or a member type / alias).

Comment on lines +26642 to +26650
if base.cached_kind() == "decltype"
&& base
.named_child(0)
.filter(|&operand| is_name(operand))
.and_then(|operand| lookup_var_node(program, ctx, source, operand))
.is_some_and(|id| ctx.forwarding_reference_parameters.contains(&id))
{
return None;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep const overloads reachable through forwarding-reference decltype

forwarding_reference_parameters is checked here in MoveForward::result_desc and in decltype_reference_kind, but MoveForward::result_constness right below still falls through to receiver_is_const(..., operand, ...) for decltype(x). Because a forwarding-reference parameter (T&& x or auto&& x) is recorded with object_const = false, result_constness returns Some(false) even though T can deduce const S& or const S.

For template<class T> void f(T&& x, const S& cs) { std::forward<decltype(x)>(cs).call(); } (and void f(auto&& x, const S& cs)), S::call() const & and S::call() const && are dropped while only non-const S::call() & and S::call() && are emitted. Return None (unknown constness) from result_constness when decltype names a forwarding_reference_parameters variable.

Comment on lines +15714 to +15730
let simple = program.base_names(class).all(&mut simple_subobject)
&& program.types.get(ty).layout.fields.values().all(|field| {
let qualification = program.types.field_qualification(class, &field.name);
if program.types.field_is_reference(class, &field.name)
|| qualification.is_some_and(|qual| qual.cv.object_const)
{
return false;
}
match peel_arrays(program.types.get(field.type_id).desc.as_ref()).0 {
TypeDesc::Struct { name, .. } => {
!qualification.is_some_and(|qual| qual.cv.object_volatile)
&& simple_subobject(name)
}
TypeDesc::Union { .. } | TypeDesc::Unknown => false,
_ => true,
}
});

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Do not prove template or anonymous-union subobjects simple for move assignment

subobjects_have_simple_assignment returns true and drops the copy-assignment fallback in two layouts where C++ implicitly deletes S& operator=(S&&) = default and calls S::operator=(const S&) on a = std::move(b):

  • A class-template subobject with a dependent field (e.g. template<class T> struct Box { T value; }; instantiated as Box<NoMove> b; or Box<const int> b;): Box::value lowers as TypeDesc::Int, so simple_subobject("Box") returns true even though the instantiated field is non-movable or const.
  • An anonymous union member (union { int x; NoMove m; };): no TypeDesc::Union field is recorded in layout.fields, so S appears to have no fields and returns true.

In both cases a = std::move(b) emits no S::operator= edge instead of retaining S::operator=(const S&).

Comment thread crates/trace-ir/src/symbol.rs Outdated
arguments: b,
complete: bc,
}),
) => ((!ac && !bc) || a.len() == b.len()) && specialization_arguments_agree(a, b),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve distinct pack-length specializations when complete is false

Gating the length comparison on complete still collapses distinct specializations with different pack lengths whenever complete is false on both sides. That happens both for a primary with a deduced parameter before a non-deduced pack (template<class T, class... U> Tag* malloc(T);) and whenever a class or namespace declares a second primary template overload of another arity (template<class... T> static Tag* malloc(int); alongside template<class T> static Tag* malloc(int, int);, making sole_allocator_primary return None).

In a multi-TU fixture declaring both malloc<int>(int) and malloc<int, long>(int) in a header, defining malloc<int> (&one) in caller.cpp and malloc<int, long> (&two) in impl.cpp, both specializations merge into one symbol during header lowering and malloc<int, long>(7) (both at file scope and in a function) points only to one and loses two.

Handle adjusted array parameters, projected glvalues, dependent and member decltype, and built-in address-of for reference binding. Keep the copy assignment candidate when a template or anonymous-union layout cannot establish move viability.

Keep allocator specializations across nested owners, wrapped declarators, written pack lengths, and database relinking. Preserve primary defaults, ranked result typing, and selected return targets with custom summaries.

Reproduced all fifteen review findings against 8246675 and added focused regressions, including separate-database export and relinking.
A specialization that spells out only leading arguments, such as
malloc<int>(int, long) for template<class T, class U> Tag* malloc(T, U),
now completes its identity from the formals that directly name the
remaining type parameters. The completed list matches a definition that
writes every argument, so the consumer call keeps the provider's
returned pointee and each database exports the same identity string.

An overload with an incompatible formal arity no longer prevents
identifying the primary. One compatibility filter now serves argument
completion and the default-expression source, so an unrelated template
overload cannot drop an inherited default or split a written list.

Regressions reproduce both findings against the pre-fix lowering and add
separate-database relinking for a completed specialization identity and
for a primary template, whose exported <template> marker keeps an
ordinary same-signature overload from stealing the relink.
Complete directly deduced pointer arguments so partially written declarations match their definitions across translation units and separately exported databases. Exclude primaries with incompatible non-dependent formal types when binding specialization defaults, while preserving uncertain dependent matches.
Complete specialization identities from lvalue-reference formals and retain the pointer shape of dependent formals when looking up the primary's defaults.

Distinguish current ordinary allocator signatures from legacy unmarked rows so supported older databases can relink to matching template definitions without relaxing known identities.
Remove only the cv qualifiers added by the primary's reference formal when completing a specialization identity. Use explicit reference bindings to distinguish reference storage from by-value pointer formals during default-source lookup.
Complete allocator specialization identities from rvalue-reference formals, preserving an lvalue reference when forwarding-reference deduction collapses. Inherit defaults from primaries whose fixed formals stay aligned before a trailing pack.

@devnullexile devnullexile left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread crates/trace-parse/src/lower.rs Outdated
if let Some(var) = static_member_access(program, ctx, source, field) {
return Some(trace_ir::FieldQualification {
cv: var_cv(program, ctx, var),
..Default::default()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve static reference members’ declared category in decltype

With struct H { static M& ref; };, std::forward<decltype(h.ref)>(h.ref).pick() should call M::pick() &. The static-member branch records only cv qualification, so decltype_reference_kind treats the member as a value type and emits only M::pick() &&. The previous head retained the lvalue edge. Preserve the static member’s declared reference category, or keep the category unknown if that metadata is unavailable.

Comment thread crates/trace-parse/src/lower.rs Outdated
@@ -6036,6 +6243,14 @@ fn lower_struct_specifier(
cv,
is_mutable,
is_reference: is_ref,
is_rvalue_reference: is_ref

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep dependent member references eligible for collapsing

Given template<class T> struct Ref { using type = M&; }; and a field typename Ref<T>::type&& ref; in H<T>, the field is an lvalue reference when instantiated. In template<class T> void run(H<T>& h, M& obj), std::forward<decltype(h.ref)>(obj).pick() now emits only M::pick() &&, dropping the valid M::pick() & edge. The written && does not establish the category when the underlying type is dependent. Preserve an unknown category until the alias can be resolved.

Comment thread crates/trace-ir/src/symbol.rs Outdated
complete: bc,
}),
) => {
(a.len() == b.len() || (!ac && !bc && (a.is_empty() || b.is_empty())))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Match partial spellings of fixed-arity specializations

For template<class T, class U> Fn malloc(T, U*);, a header can declare template<> Fn malloc<int>(int, long*); and a provider TU can define template<> Fn malloc<int, long>(int, long*). These name the same specialization because the declaration deduces U = long. The new length check splits the rows because normalization cannot deduce through U*. A caller in another TU now reaches only an undefined declaration and loses the callback returned by the definition. Allow compatible prefixes when a fixed-arity primary leaves arguments to be deduced, while keeping the distinct pack-length cases separate.

Comment thread crates/trace-merge/src/lib.rs Outdated
let (b_storage, b) = allocator_signature_parts(b);
match (a, b) {
(Some(a), Some(b)) => {
a == b

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep unresolved specialization arguments compatible during relinking

With template<int N> int* malloc(int); in both inputs, a caller database declaring and calling malloc<1 + 1> exports <specialized<?>>, while a provider defining malloc<2> exports <specialized<2>>. The merged call now stays external even though the provider body is present. Apply the in-memory compatibility rule for unresolved slots when comparing exported identities, so ? can match a concrete argument without conflating different known values.

}
}
}
if !same_type.is_empty() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Apply strong-over-weak selection across allocator signature versions

Merge a caller database with a weak app::malloc(int) definition and a provider database with the equivalent strong definition. When exactly one input comes from before the <ordinary> marker, the call keeps the weak target because the exact-signature bucket excludes the other spelling before strength selection. Both mixed-version directions reproduce this, and matching exporter versions select the strong definition. Treat matching marked and legacy ordinary signatures as equivalent for strength selection.

@DrSergei DrSergei left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Union LHS misses user-defined operator= — lower.rs:17527 matches only TypeDesc::Struct, while the copy-init path accepts unions, so union U { U& operator=(const U&); }; a = b; emits 0 call edges despite an indexed body. Real under-approximation; include Union and verify subobjects_have_simple_assignment handles union owners.
  2. Template/overload collapse is allocator-only — symbol.rs:2395 gates the is_free_function_template identity check on is_allocator_name, but same_template_signature, has_same_signature, and initializer_declaration_candidates apply it to every name. A non-allocator template void f(int); and void f(int); merge into one row, and calls bind to the non-template definition. Extend the guard to all names (keep the export marker allocator-only).
  3. Minor — dataflow.rs:56's !signature.ends_with("()") heuristic reports "parameters unavailable" for zero-arg functions carrying the new / markers; compare the storage signature before markers.

@ArcsinX ArcsinX left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed up to a71bcde02ccd44e171abe314cb4fb37d3365df64.

Resolved 5 addressed ArcsinX threads:

  • decltype_reference_kind now checks forwarding_reference_parameters for T&& / auto&&.
  • has_same_signature now checks same_template_signature.
  • lower_class_assignment now keeps the copy fallback when a defaulted move assignment is not proven simple.
  • lower_copy_initialization now relies on initializer_glvalue for compound glvalues.
  • same_allocator_specialization now checks argument-list length.

Still unaddressed:

  • Out-of-class member allocator specialization declarations in lower_function_decl still omit this and fail to merge with lower_function_signature definitions.

Also added 1 minor inline note on lower_one_declarator (volatile auto&&).

let category = declared_reference_kind(program, ctx, source, Some(decl), ty);
let category = if category == Some(true)
&& ty.is_some_and(|ty| is_placeholder_type(ctx, ty))
&& !declaration_has_const(source, declaration)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: volatile auto&& is treated as a forwarding reference

lower_one_declarator checks !declaration_has_const(source, declaration) before deriving the reference category from init_expr, but does not check !declaration_has_qualifier(source, declaration, "volatile") (unlike lower_parameter at line 9425). In C++, volatile auto&& is a volatile rvalue reference rather than a forwarding reference, so decltype(x) is always &&.

Comment on lines +414 to +421
let mut compatible = declarations.iter().copied().filter(|&id| {
references.is_empty()
|| trace_ir::split_signature_references(signature_of(id))
.1
.is_empty()
});
let first = compatible.next()?;
compatible.next().is_none().then_some(first)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Legacy declaration merge defeated by duplicate entries

shared_declaration accepts an unannotated legacy declaration only when its filtered input list has exactly one entry (compatible.next().is_none()). However header_decl_map is filled with push(new_fn_id) for every input copy, including copies that were merged into the same existing row, so the vector can hold the same id more than once. When three or more input databases share one declaration origin and the suffix-bearing copy is processed after two suffix-less copies of the same signature have merged into one row, the list is e.g. [A, A]. The current copy does not match exactly, annotated_origins still reports a single annotated signature (so allow_legacy_match is true), but the uniqueness check sees two entries and returns None, so the current declaration is added as a second row at the same file/line instead of updating the shared legacy row. Consequence: a mixed-version merge of an old database with another old one and a new one can retain duplicate external declarations at one origin, which can make relinking of calls to that declaration ambiguous or bind them to the stale unannotated row. Fix: compare distinct ids (e.g. compatible.all(|id| id == first)) or deduplicate the declaration ids before the uniqueness check.

@devnullexile devnullexile left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@@ -6171,6 +6381,18 @@ fn register_static_data_member(
true,
);
program.var_qualifications.insert(var_id, cv);
let reference_category =
data_member_reference_category(program, ctx, source, field, decl);
program.types.note_field_qualification(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep static member reference categories scoped to the class specialization

Given template<class T> struct H { static M&& ref; }; and template<> struct H<int> { static M& ref; };, std::forward<decltype(h.ref)>(h.ref).pick() on an H<double>& h now emits only M::pick() &. Clang and the previous head select M::pick() &&. The new field metadata stores both declarations under the same owner and member key, so the explicit specialization overwrites the primary’s category. Use the receiver’s actual class specialization to look up the declaration before narrowing the overloads.

// when the declaration cannot supply the deduced suffix.
if args.len() < deduced_types.len() {
padded_from = Some(args.len());
args.resize(deduced_types.len(), None);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Resolve defaulted template arguments before padding allocator identities

With template<class T, class U = int> void* malloc(int);, a provider definition spelled malloc<char>(int) defines malloc<char, int>. Merging that database with a caller database that selects malloc<char, long>(int) now turns an external edge into a direct edge to the provider’s different specialization. The padded <specialized-fixed<char,~>> erases the known default, and relinking treats it as compatible with long. Record the default when a missing slot is determined by the primary’s template parameter default.

|| a == OMITTED_SPECIALIZATION_ARGUMENT
|| b == OMITTED_SPECIALIZATION_ARGUMENT
// A fixed integral argument carries only its value.
|| a.split_once(':').is_some_and(|(value, _)| value == b && b.parse::<i128>().is_ok())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve integral parameter types when relinking specializations

A caller database declaring template<unsigned N> int* malloc(int); and the explicit specialization malloc<1>(int) now links to a provider defining malloc<1>(int) under template<auto N>. The caller requires an unsigned template argument and the provider defines an int template argument. Clang emits different symbols for them. The new comparison equates the two exports (1 and 1:Int) by value and creates a direct edge where the previous head kept it external. Preserve the fixed parameter’s type or restrict this fallback to cases where the argument types can agree.

else {
return None;
};
if arguments.is_empty() && !complete {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Record a known empty allocator pack for a zero-parameter specialization

For template<class... T> void* malloc(T*...); followed by template<> void* malloc<>() { return nullptr; }, the zero-parameter signature fixes the pack length at zero. The export still writes the unknown <specialized> marker, which now prevents two such definitions from competing on strength. Merging a weak copy with a strong copy leaves the call ambiguous between both, where the previous head selected the strong definition. Record the known empty pack so this case can use normal strong-over-weak selection.

let (candidate, candidate_references) =
trace_ir::split_signature_references(&def.signature);
if trace_ir::signature_references_compatible(references, candidate_references) {
if !unknown && linkage_signature(candidate).0 == signature_key {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep template candidates for unmarked allocator declarations

When a legacy caller row has the bare signature app::malloc(int) and the inputs provide both marked <ordinary> and <template> definitions with that storage, the ordinary definition enters the exact-match pool and the template is dropped. I reproduced a direct edge to the ordinary body for a legacy database whose source calls app::malloc<char>(0). The previous head kept both candidates because the old signature cannot distinguish them. Keep same-storage template candidates for unmarked callers when their identity is ambiguous, while still applying strong-over-weak selection among ordinary definitions.

@ArcsinX ArcsinX left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed up to 80f28cd.

  • Resolved the ArcsinX thread on lower_function_decl out-of-class member allocator specialization declarations: SymbolTable::redeclaration_compatible (crates/trace-ir/src/symbol.rs:2569) now handles allocator_specialization_args().is_some() via explicit_arity and explicit_params_with.
  • Kept the minor volatile auto&& thread (crates/trace-parse/src/lower.rs:15348) open.
  • Added 1 new inline comment on MoveForward::is_rvalue (crates/trace-parse/src/lower.rs:26834) for std::forward<decltype(x)*>(p).

let reference = declaration_reference_kind(program, ctx, source, explicit)
.or_else(|| type_reference_kind(program, ctx, source, ty));
if reference == Some(false) {
return reference;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MoveForward::is_rvalue treats std::forward<decltype(x)*>(p) as an lvalue when decltype(x) is an lvalue reference

ty is explicit.cached_field("type").unwrap_or(explicit), so for std::forward<decltype(x)*>(p) or std::forward<decltype(x)*&&>(p) (where x is S& x; or decltype((x))*), ty.cached_kind() is "decltype" and declaration_reference_kind is None (or Some(true)). Unlike MoveForward::result_constness (which checks added_pointers), is_rvalue enters if ty.cached_kind() == "decltype" without checking whether explicit has a pointer declarator, so decltype_reference_kind returns Some(Some(false)) and is_rvalue classifies the pointer rvalue as an lvalue (Some(false)) instead of an rvalue (Some(true)).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants